package com.bscc.admin.menu;

import com.bscc.common.model.Menu;
import com.jfinal.plugin.activerecord.Db;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class MenuService
{
    private static final Menu dao = new Menu().dao();

    public List<Menu> findList()
    {
        List<Menu> menuList = dao.find("SELECT * FROM bw_menu ORDER BY sort");
//        countChild(menuList);
        List<Menu> sortedList = new ArrayList<Menu>();
        sortForTree(sortedList, menuList, 0);
        return sortedList;
    }

    public Menu findById(int id)
    {
        Menu menu = dao.findById(id);
        if(null != menu && null != menu.getPid() && 0 != menu.getPid())
        {
            Menu pMenu = dao.findById(menu.getPid());
            if(null != pMenu)
            {
                menu.setPname(pMenu.getName());
            }
        }
        return menu;
    }


    public void deleteById(int id)
    {
        String pids = findById(id).getPids();
        Db.update("DELETE FROM bw_menu WHERE pids LIKE ?", pids+"%");
    }

    public void save(Menu menu)
    {
        menu.save();
        if(null == menu.getPid() || 0 == menu.getPid())
        {
            menu.setPid(0);
            menu.setPids("0,"+menu.getId());
        }
        else
        {
            Menu parent = findById(menu.getPid());
            if(null != parent && StringUtils.isNotBlank(parent.getPids()))
                menu.setPids(parent.getPids()+","+menu.getId());
        }
        menu.update();
    }

    public void update(Menu menu)
    {
        menu.update();
    }

    private void countChild(List<Menu> menuList)
    {
        if(null != menuList && menuList.size() > 0)
        {
            for(int i=0; i < menuList.size(); ++i)
            {
                int count = 0;
                for(Menu m:menuList)
                {
                    if(m.getPid().equals(menuList.get(i).getId()))
                        ++count;
                }
                menuList.get(i).setChildCount(count);
            }
        }
    }

    public void sortForTree(List<Menu> res, List<Menu> src, int pid)
    {
        if(null != src && src.size() > 0)
        {
            for(Menu m: src)
            {
                if(pid == m.getPid())
                {
                    res.add(m);
                    sortForTree(res, src, m.getId());
                }
            }
        }
    }
}
